package jprint.jfx.webapp;

import java.io.IOException;
import java.net.URL;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.Pane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

/**
 * @author zwz
 * Created on 2021-01-21
 */
class WebViewController {

    // java 9+ 访问模块内的资源始终以/开头
    private static final String sFxmlPath = "/jfx_webview.fxml";
    private Scene scene;
    @FXML MenuBar mbMain;
    // @FXML
    MenuItem miDebug;
    @FXML MenuItem miExit;
    @FXML private WebView webview;
    private WebEngine engine;

    WebViewController() throws IOException {
        /*sInstance = this;*/
        URL url = getClass().getResource(sFxmlPath);
        FXMLLoader loader = new FXMLLoader(url);
        loader.setController(this);
        Parent root = loader.load();
        scene = new Scene(root);
        initUI();
    }

    private void initUI() {
        mbMain.setVisible(false);
        Pane pane = (Pane) mbMain.getParent();
        pane.getChildren().remove(0);
    }

    Scene getScene() {
        return scene;
    }

    public WebView getWebView() {
        return webview;
    }

    public void loadUrl(String url) {
        if (engine == null) engine = webview.getEngine();
        engine.load(url);
    }

    public void executeScript(final String script, ScriptCallback callback) {
        if (engine == null) engine = webview.getEngine();
        Platform.runLater(() -> {
            Object obj = engine.executeScript(script);
            if (callback != null) callback.handle(obj);
        });
    }
}
